package com.ygqh.baby.controller.admin;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.ContractStatus;
import com.ygqh.baby.ao.FileType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.model.AdminContract4ImportModel;
import com.ygqh.baby.po.AdminContract;
import com.ygqh.baby.po.AdminSku;
import com.ygqh.baby.po.AdminSupplementContract;
import com.ygqh.baby.po.YgCategory;
import com.ygqh.baby.service.AdminContractService;
import com.ygqh.baby.service.AdminSkuService;
import com.ygqh.baby.service.AdminSupplementContractService;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.YgCategoryService;
import com.ygqh.baby.shiro.utils.SessionUtil;

/**
 * Created by ZhangSai on 2016/11/4 0004.
 */

@Controller
@RequestMapping("/admin/contract")
public class ContractController extends BaseController<Object, Object> {
	@Autowired
	private YgCategoryService categoryService;
	@Autowired
	protected FileService fileService;
	@Autowired
	private AdminContractService contractService;

	@Autowired
	private AdminSkuService adminSkuService;
	@Autowired
	private AdminSupplementContractService supplementContractService;

	@RequestMapping("findCategory")
	@ResponseBody
	public List<YgCategory> findCategory() {
		return categoryService.findCategoryByLevel(2L);
	}

	/**
	 * 下载大货合同模板
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("downloadGoodsContractTemplate")
	public void downloadGoodsContractTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		byte[] bytes = fileService.downloadFromOss("template/yiigoo_goods_contract_template.xlsx");
		DocumentHandler.createDownload(bytes, "壹果大货合同详明细.xlsx", request, response);
	}

	/**
	 * 下载大货合同模板
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("downloadMaterialTemplate")
	public void downloadMaterialTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		byte[] bytes = fileService.downloadFromOss("template/yiigoo_material_contract_template.xlsx");
		DocumentHandler.createDownload(bytes, "壹果物料合同明细.xlsx", request, response);
	}

	@RequestMapping("loadDetail")
	@ResponseBody
	public Message loadDetail(@RequestParam("contractType") String contractType, @RequestParam("uploadFile") MultipartFile uploadFile,
			HttpServletRequest request, HttpServletResponse respons) throws IOException {

		InputStream is = uploadFile.getInputStream();
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

		List<AdminContract4ImportModel> orderList = new ArrayList<>();
		try {
			// Read the Sheet
			for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
				if (xssfSheet == null) {
					continue;
				}

				List<String> skuCodeList = new ArrayList<>();

				// Read the Row
				for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					if (xssfRow != null && xssfRow.getPhysicalNumberOfCells() >= 8) {
						XSSFCell skuCode = xssfRow.getCell(0);
						XSSFCell outCode = xssfRow.getCell(1);
						XSSFCell productName = xssfRow.getCell(2);
						XSSFCell color = xssfRow.getCell(3);
						XSSFCell quantity = xssfRow.getCell(4);
						XSSFCell sizeName = xssfRow.getCell(5);
						XSSFCell price = xssfRow.getCell(6);
						XSSFCell arrivedDate = xssfRow.getCell(7);
						XSSFCell isNewProductStr = xssfRow.getCell(8);

						AdminContract4ImportModel model = new AdminContract4ImportModel();
						model.setSkuCode(Double.valueOf(getValue(skuCode)).longValue() + "");
						model.setOutCode(getValue(outCode));
						model.setProductName(getValue(productName));
						model.setColor(getValue(color));
						model.setSizeName(getValue(sizeName));
						
						model.setQuantity(quantity == null ? null : new BigDecimal(getValue(quantity)));
						model.setPrice(price == null ? null : new BigDecimal(getValue(price)));
						Date date = null;
						try {
							date = arrivedDate == null ? null : arrivedDate.getDateCellValue();
						} catch (Exception e) {

						}
						model.setArrivedDate(date);
						model.setRemark("");
						String tmp = getValue(isNewProductStr);
						Boolean isNewProduct = null;
						if (tmp != null && tmp.equals("是")) {
							isNewProduct = true;
						} else if (tmp != null && tmp.equals("否")) {
							isNewProduct = false;
						}
						model.setNewProduct(isNewProduct);
						checkData(model, contractType);
						if (skuCodeList.contains(model.getSkuCode())) {
							model.setRemark(model.getRemark() + "sku重复;");
						} else {
							skuCodeList.add(model.getSkuCode());
						}
						AdminSku sku = adminSkuService.findBySkuCode(model.getSkuCode());
						if (sku == null) {
							model.setRemark(model.getRemark() + "sku不存在;");
						} else {
							model.setColor(sku.getColor());
							model.setSizeName(sku.getSizeName());
							model.setProductName(sku.getProductName());
						}

						AdminContract4ImportModel dbModel = null;

						orderList.add(model);

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error(orderList);
		}

		return Message.success(orderList);
	}

	private void checkData(AdminContract4ImportModel model, String contractType) {
		StringBuilder remark = new StringBuilder();
		if (model.getSkuCode() == null) {
			remark.append("请填写有效的SKU;");
		}

		if (model.getQuantity() == null || model.getQuantity().intValue() <= 0) {
			remark.append("请填写有效的数量;");
		}

		if (model.getPrice() == null) {
			remark.append("请填写单价");
		} else {
			if (model.getPrice().compareTo(BigDecimal.ZERO) == 0 || model.getPrice().compareTo(BigDecimal.ZERO) == -1) {
				remark.append("单价必须大于0");
			}
		}

		if (model.getArrivedDate() == null) {
			remark.append("请填写预计到货日期");
		}

		model.setRemark(remark.toString());
	}

	/**
	 * 得到Excel表中的值
	 *
	 * @param hssfCell
	 *            Excel中的每一个格子
	 * @return Excel中每一个格子中的值
	 */
	@SuppressWarnings("static-access")
	private String getValue(XSSFCell hssfCell) {
		if (hssfCell == null)
			return null;
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			DecimalFormat df = new DecimalFormat("0.00");
			String str = df.format(hssfCell.getNumericCellValue());
			// 返回数值类型的值
			return str;
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}

	/**
	 * 查找合同列表通过 供应商id
	 * 
	 * @param supplierId
	 * @return
	 */
	@RequestMapping("findContractListBySupplier")
	@ResponseBody
	public List<AdminContract> findContractListBySupplier(@RequestParam Long supplierId) throws IOException {
		List<AdminContract> list = contractService.findContractListBySupplier(supplierId);
		return list;
	}

	@RequestMapping("saveContract")
	@ResponseBody
	public Message saveContract(@RequestParam String contractStr) throws IOException {
		AdminContract adminContract = JSON.parseObject(contractStr, AdminContract.class);
		String operator = SessionUtil.getCurrentUser().getTrueName();
		adminContract.setPrePercent(adminContract.getPrePercent().divide(new BigDecimal(100)));
		adminContract.setPickPercent(adminContract.getPickPercent().divide(new BigDecimal(100)));
		adminContract.setEndPercent(adminContract.getEndPercent().divide(new BigDecimal(100)));
		contractService.saveOrUpdate(adminContract, operator);
		return Message.success(null);
	}

	@RequestMapping("searchContract")
	@ResponseBody
	public Map<String, Object> searchContract(String q, QueryInfo queryInfo, Date startDate, Date endDate, ContractStatus contractStatus,
											  String contractType,String productName,String contractCode, String skuCode) throws ParseException {

		ResultSet<AdminContract> resultSet = contractService.search(queryInfo, q, startDate, endDate, contractStatus,
				contractType,productName,contractCode, skuCode);

		return resultSet.toDatatables(null);
	}

	@RequestMapping("updateContractStatus")
	@ResponseBody
	public Message updateContractStatus(Long id) {
		AdminContract contract = new AdminContract();
		contract.setId(id);
		contract.setContractStatus(ContractStatus.Completed);
		contract.setUpdateTime(new Date());
		contract.setUpdateBy(SessionUtil.getCurrentUser().getTrueName());
		contractService.update(contract);
		return Message.success(null);
	}

	@RequestMapping("findDetailById")
	@ResponseBody
	public AdminContract findDetailById(Long id) throws ParseException {

		AdminContract contract = contractService.findDetailById(id);

		return contract;
	}

	/**
	 * 合同删除
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("deleteContract")
	@ResponseBody
	public Message deleteContract(@RequestParam Long id) throws IOException {
		String operator = SessionUtil.getCurrentUser().getTrueName();
		Message message = contractService.deleteContract(id, operator);
		return message;
	}

	/**
	 * 合同归档
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("archivedContract")
	@ResponseBody
	public Message archivedContract(@RequestParam Long id, String contractCode) throws IOException {
		String operator = SessionUtil.getCurrentUser().getTrueName();
		Message message = contractService.archivedContract(id, operator, contractCode);
		return message;
	}

	/**
	 * 合同作废
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("cancelContract")
	@ResponseBody
	public Message cancelContract(@RequestParam Long id, String cancelReason) throws IOException {
		String operator = SessionUtil.getCurrentUser().getTrueName();
		Message message = contractService.cancelContract(id, operator, cancelReason);
		return message;
	}

	/**
	 * 修改备注
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("updateRemark")
	@ResponseBody
	public Message updateRemark(@RequestParam Long id, String remark) throws IOException {
		System.err.println(remark);
		String operator = SessionUtil.getCurrentUser().getTrueName();
		AdminContract adminContract = contractService.findById(id);
		adminContract.setRemark(remark);
		Message message = contractService.updateRemark(id, operator, remark);
		return message;
	}

	@RequestMapping("findById")
	@ResponseBody
	public AdminContract findById(@RequestParam Long id) throws IOException {
		AdminContract adminContract = contractService.findById(id);
		return adminContract;
	}

	@RequestMapping("findByCode")
	@ResponseBody
	public AdminContract findByCode(@RequestParam String code) throws IOException {
		AdminContract adminContract = contractService.findByCode(code);
		return adminContract;
	}

	@RequestMapping("saveSupplementContract")
	@ResponseBody
	public Message saveSupplementContract(@RequestParam String contractStr) throws IOException {
		AdminSupplementContract contract = JSON.parseObject(contractStr, AdminSupplementContract.class);
		String operator = SessionUtil.getCurrentUser().getTrueName();
		return supplementContractService.saveOrUpdate(contract, operator);
	}

	@RequestMapping("searchSettlementContract")
	@ResponseBody
	public Map<String, Object> searchSettlementContract(String q, QueryInfo queryInfo, String changeContractCode) throws ParseException {

		ResultSet<AdminSupplementContract> resultSet = supplementContractService.search(queryInfo, q, changeContractCode);

		return resultSet.toDatatables(null);
	}

	/**
	 * 补充合同归档
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("archivedSettlementContract")
	@ResponseBody
	public Message archivedSettlementContract(@RequestParam Long id, String contractCode) throws IOException {
		String operator = SessionUtil.getCurrentUser().getTrueName();
		Message message = supplementContractService.archivedContract(id, operator, contractCode);
		return message;
	}

	/**
	 * 补充合同删除
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("deleteSettlementContract")
	@ResponseBody
	public Message deleteSettlementContract(@RequestParam Long id) throws IOException {
		String operator = SessionUtil.getCurrentUser().getTrueName();
		Message message = supplementContractService.deleteSettlementContract(id, operator);
		return message;
	}

	/**
	 * 补充修改备注
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("updateSettlementRemark")
	@ResponseBody
	public Message updateSettlementRemark(@RequestParam Long id, String remark) throws IOException {
		String operator = SessionUtil.getCurrentUser().getTrueName();
		AdminSupplementContract adminContract = supplementContractService.findById(id);
		adminContract.setRemark(remark);
		Message message = supplementContractService.updateSettlementRemark(id, operator, remark);
		return message;
	}

	@RequestMapping("findSupplementDetailById")
	@ResponseBody
	public AdminSupplementContract findSupplementDetailById(@RequestParam Long id) throws IOException {
		AdminSupplementContract adminContract = supplementContractService.findDetailById(id);
		return adminContract;
	}
	@RequestMapping("downloadContract")
	public void downloadContract(HttpServletRequest request, HttpServletResponse response,String contractCode,FileType fileType) throws IOException {
		byte[] bytes = fileService.downloadFromOss(fileType+"/"+contractCode+".pdf");
		DocumentHandler.createDownload(bytes, contractCode+".pdf", request, response);
	}
	
	@RequestMapping("upLoadContract")
	@ResponseBody
	public Message upLoadContract(Long id,String contractCode,FileType fileType,@RequestParam("uploadFile")   MultipartFile uploadFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		String url=fileService.upload2Oss(fileType, uploadFile,contractCode);
		if(url.length()>0){
			if(fileType.equals(FileType.Contract)){
				AdminContract adminContract=new AdminContract();
				adminContract.setId(id);
				adminContract.setIsUpload(true);
				contractService.update(adminContract);
			}else{
				AdminSupplementContract adminSupplementContract=new AdminSupplementContract();
				adminSupplementContract.setId(id);
				adminSupplementContract.setIsUpload(true);
				supplementContractService.updateMain(adminSupplementContract);
			}
		}
		return SUCCESS_MESSAGE;
	}
	@RequestMapping("getContractCode")
	@ResponseBody
	public String getContractCode(String frameCode){
		return contractService.findContractCode(frameCode);
		
	}
	@RequestMapping("printContract")
	public void printContract(Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		AdminContract contract= contractService.findDetailById(id);
	
		byte[] bytes = fileService.downloadFromOss("template/contract_print.xlsx"); 
		List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
		Map<String, Object> dataMap = new HashMap<String, Object>();

		dataMap.put("contractCode", contract.getContractCode());
		dataMap.put("supplierName", contract.getAdminSupplier().getSupplierName());
		dataMap.put("contractPrice", contract.getContractPrice());
		
		dataMaps.add(dataMap);
		DocumentHandler.DownloadExcel(bytes, "合同审批单.xlsx", dataMap, request, response);
	}
	

}
